import 'package:flutter/material.dart';

class CommonUtils {
  /// 坐标转换为点位的索引坐标
  static double coverPoint2Idx(double point, double width) {
    return (point / width).floor().toDouble();
  }

  /// 点位的索引坐标转换为坐标
  static double coverPointIdx2Point(double idx, double width) {
    return idx * width + width / 2;
  }

  /// 16进制转颜色
  static Color hex2Color(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll("#", "");
    if (hexColor.length == 6) {
      hexColor = "FF$hexColor";
    }
    return Color(int.parse(hexColor, radix: 16));
  }

  /// 颜色转16进制
  static String color2Hex(Color color) {
    return "#${color.toARGB32().toRadixString(16)}";
  }

  /// HSL转颜色
  static Color hsl2Color(double a, double h, double s, double l) {
    return HSLColor.fromAHSL(
      a,
      h.clamp(0.0, 360.0),
      s.clamp(0.0, 100.0) / 100.0,
      l.clamp(0.0, 100.0) / 100.0,
    ).toColor();
  }

  /// ARGB转颜色
  static Color argb2Color2(double a, int r, int g, int b) {
    return Color.fromRGBO(r.clamp(0, 255), g.clamp(0, 255), b.clamp(0, 255), a);
  }

  /// 双层Map添加数据
  static void map2Put(
    Map<double, Map<double, Color>> map,
    double x,
    double y,
    Color color,
  ) {
    if (!map.containsKey(x)) {
      map[x] = <double, Color>{};
    }
    map[x]![y] = color;
  }

  /// 双层Map添加数据
  /// 仅元素为null时添加
  static void map2PutOnlyNull(
    Map<double, Map<double, Color>> map,
    double x,
    double y,
    Color color,
  ) {
    if (!map.containsKey(x)) {
      map[x] = <double, Color>{};
    }
    if (map[x]![y] == null) {
      map[x]![y] = color;
    }
  }

  /// 双层Map获取数据
  static Color? map2Get(
    Map<double, Map<double, Color>> map,
    double x,
    double y,
  ) {
    if (map.containsKey(x)) {
      if (map[x]!.containsKey(y)) {
        return map[x]![y];
      }
    }
    return null;
  }

  /// 双层Map迭代
  static void map2Iterable(
    Map<double, Map<double, Color>> map,
    Function(double x, double y, Color color) callback,
  ) {
    map.forEach((x, yMap) {
      yMap.forEach((y, color) {
        callback(x, y, color);
      });
    });
  }

  /// 显示Toast
  static void showToast(String message, context) {
    final scaffold = ScaffoldMessenger.of(context);
    scaffold.hideCurrentSnackBar();
    scaffold.showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 1),
        behavior: SnackBarBehavior.floating,
        margin: const EdgeInsets.all(16.0),
        backgroundColor: Colors.black54,
        elevation: 0,
      ),
    );
  }
}
